package cn.py.boot_lua.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.*;
import java.util.logging.Logger;

@Component
public class GetPathSerHelper {
    private static final Logger log = Logger.getLogger(GetPathSerHelper.class.getName());

    @Value("${temporary.files.path}")
    private String temporaryFilesPath;

    public String getPath(String catalog) {
        String baseDir = System.getProperty("user.dir");
        String fullPath = Paths.get(baseDir, temporaryFilesPath, catalog).toString();
        return createDirectory(fullPath);
    }

    private String createDirectory(String pathStr) {
        Path path = Paths.get(pathStr);

        if (Files.exists(path)) {
            log.info("目录已存在：" + pathStr);
            if (!pathStr.endsWith("/")) {
                return pathStr + "/";
            }
            return pathStr;
        }

        try {
            Files.createDirectories(path);
            log.info("目录创建成功：" + pathStr);
        } catch (IOException e) {
            log.severe("无法创建目录：" + pathStr + " - 错误信息：" + e.getMessage());
            throw new RuntimeException("目录创建失败: " + e.getMessage());
        }

        return pathStr.endsWith("/") ? pathStr : pathStr + "/";
    }
}
